import 'package:enjoy_plus_ohos/utils/http.dart';
import 'package:enjoy_plus_ohos/utils/toast.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  @override
  void initState() {
    super.initState();
    requestLocationPermission();
  }

  // 申请权限
  Future<void> requestLocationPermission() async {
    PermissionStatus status = await Permission.location.request();
    if (status.isGranted) {
      ToastUtil.showSuccess('位置权限授予');
    } else {
      ToastUtil.showError('位置权限未授予, 请去设置中心开启');
    }
  }

  // 定位
  Future<void> getCurrentLocation() async {
    late LocationSettings locationSettings;

    if (defaultTargetPlatform == TargetPlatform.android) {
      // 针对Android平台，设置高精度定位、100米距离过滤、强制使用位置管理器等
      locationSettings = AndroidSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
        forceLocationManager: true,
        intervalDuration: const Duration(seconds: 10),
        foregroundNotificationConfig: const ForegroundNotificationConfig(
          notificationText:
              "Example app will continue to receive your location even when you aren't using it",
          notificationTitle: "Running in Background",
          enableWakeLock: true,
        ),
      );
    } else if (defaultTargetPlatform == TargetPlatform.iOS ||
        defaultTargetPlatform == TargetPlatform.macOS) {
      // 针对iOS和macOS平台，设置高精度定位、健身活动类型、100米距离过滤等
      locationSettings = AppleSettings(
        accuracy: LocationAccuracy.high,
        activityType: ActivityType.fitness,
        distanceFilter: 100,
        pauseLocationUpdatesAutomatically: true,
        // 只有在应用在后台启动时才设置为true
        showBackgroundLocationIndicator: false,
      );
    } else if (kIsWeb) {
      // 针对Web环境，设置高精度定位、100米距离过滤、5分钟的最大年龄等
      locationSettings = WebSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
        maximumAge: const Duration(minutes: 5),
      );
    } else {
      // 对于其他平台，默认设置高精度定位和100米距离过滤
      locationSettings = const LocationSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
      );
    }
    _reverseGeocoding(113.918709, 22.645298);
    _searchPlaceAround(113.918709, 22.645298);
    // print('run');
    try {
      // 使用配置好的定位设置获取当前位置
      Position position = await Geolocator.getCurrentPosition(
        locationSettings: locationSettings,
      );
      // 显示成功获取到的纬度和经度
      ToastUtil.showSuccess('${position.latitude}, ${position.longitude}');
      // 113.918709,22.645298
      // 能拿到 就用真实的 拿不到 就用写死的
      _reverseGeocoding(position.longitude, position.latitude);
      _searchPlaceAround(position.longitude, position.latitude);
    } catch (e) {
      // 处理可能出现的异常
      print(e.toString());
    }
    // print('run');
  }

  // 逆地理编码地址结果
  String address = '';

  // 逆地理编码
  Future<void> _reverseGeocoding(double longitude, double latitude) async {
    try {
      final response = await http.get(
        // 逆地理编码 API 服务地址
        'https://restapi.amap.com/v3/geocode/regeo',
        // 请求参数
        params: {
          // 高德地图官网开发者控制台申请的密钥
          'key': '0d6687ba00dcee1b9c08525bb7e6128d', // 花姐的 key
          // 经度在前，纬度在后，经纬度间以“,”分割
          'location': '$longitude,$latitude',
          // 搜索半径
          'radius': 500,
          // 搜索类型
          'type': '住宅小区',
        },
      );
      // 更新地址信息
      setState(() {
        address = response['regeocode']['formatted_address'];
      });
      print(response);
    } catch (e) {
      print('_reverseGeocoding 逆地理编码 error');
      print(e);
    }
  }

  // 附近小区列表
  List nearbyCommunities = [];
  // 搜索周边小区
  Future<void> _searchPlaceAround(double longitude, double latitude) async {
    try {
      final response = await http.get(
        // 周边搜索API服务地址
        'https://restapi.amap.com/v3/place/around',
        params: {
          'key': '23a08cd3b7f19398c6415dcd6bb24b4b',
          'location': '$longitude,$latitude',
          'keywords': '住宅小区',
          'radius': 500,
        },
      );
      setState(() {
        // 保存列表
        nearbyCommunities = response['pois'];
      });
      print(response);
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('选择社区')),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          const Row(
            children: [Text('当前地址', style: TextStyle(color: Colors.grey))],
          ),
          const SizedBox(height: 10),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(10),
            child: Row(
              children: [
                Expanded(child: Text(address)),
                GestureDetector(
                  onTap: () {
                    getCurrentLocation();
                  },
                  child: Row(
                    children: [
                      Icon(
                        Icons.location_searching_outlined,
                        color: Colors.blue,
                      ),
                      SizedBox(width: 2),
                      Text('重新定位', style: TextStyle(color: Colors.blue)),
                    ],
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 10),
          const Row(
            children: [Text('附近社区', style: TextStyle(color: Colors.grey))],
          ),
          const SizedBox(height: 10),
          ListView(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            children: [
              ...nearbyCommunities.map((item) {
                return GestureDetector(
                  onTap: () {
                    Navigator.pushNamed(
                      context,
                      '/building_list',
                      arguments: {'point': item['name']},
                    );
                  },
                  child: Container(
                    color: Colors.white,
                    padding: const EdgeInsets.all(10),
                    child: Row(
                      children: [
                        Expanded(
                          child: Text(
                            '${item['cityname']}${item['adname']}${item['name']}',
                          ),
                        ),
                        Row(
                          children: [
                            Icon(
                              Icons.arrow_forward_ios,
                              size: 16,
                              color: Colors.black,
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                );
              }),
            ],
          ),
        ],
      ),
    );
  }
}
